﻿using Max.PH6_2009A.LowCode.Common;
using Max.PH6_2009A.LowCode.IRespository;
using Max.PH6_2009A.LowCode.IService;
using System.Data;

namespace Max.PH6_2009A.LowCode.Service
{
    public class BaseService<T> : IBaseService<T> where T : class, new()
    {
        IBaseRespository<T> _respository;

        public BaseService(IBaseRespository<T> respository)
        {
            _respository = respository;
        }
        #region 泛型反射操作
        public int Delete(List<T> t)
        {
            var tableName = ReflecationHelper.GetEntityTableName<T>();
            string sql = $"delete from {tableName}";

            var result = _respository.Execute(sql, t);
            return result;
        }

        public int Insert(T t)
        {
            string sql = ReflecationHelper.GetDapperInsertSqlString(t);
            var result = _respository.Execute(sql, t);
            return result;
        }

        public int Insert(List<T> t)
        {
            string sql = ReflecationHelper.GetDapperInsertSqlString(t[0]);
            var result = _respository.Execute(sql, t);
            return result;
        }

        public IEnumerable<T> Select()
        {
            string sql = $"select * from {ReflecationHelper.GetEntityTableName<T>()}";
            var result = _respository.Query(sql);
            return result;
        }

        public IEnumerable<T> Select(object param)
        {
            string sql = $"select * from {ReflecationHelper.GetEntityTableName<T>()}";
            var result = _respository.Query(sql, param);
            return result;
        }


        public int Update(T t)
        {
            string sql = ReflecationHelper.GetDapperUpdateSqlString(t);
            var result = _respository.Execute(sql, t);
            return result;
        }

        #endregion

        #region SQL操作

        public int Insert(string sql, object param, IDbTransaction tran = null)
        {
            int result = _respository.Execute(sql, param);
            return result;
        }
        public int Update(string sql, object param, IDbTransaction tran = null)
        {
            int result = _respository.Execute(sql, param);
            return result;
        }
        public int Delete(string sql, object param, IDbTransaction tran = null)
        {
            int result = _respository.Execute(sql, param);
            return result;
        }

        public IEnumerable<T> Select(string sql, object param)
        {
            var result = _respository.Query(sql, param);
            return result;
        }
        public IEnumerable<T> Select(string sql, object param,CommandType commandType =  CommandType.StoredProcedure)
        {
            var result = _respository.Query(sql, param,commandType);
            return result;
        }
        #endregion
    }
}